<template>
  <div class="page-common-layout">
    <div class="page-common-left" style="width:30%;padding: 0">
      <div class="header">
        <span class="title">{{$ct("menuName","菜单名称")}}</span>
      </div>
      <div class="padding-xs">
        <a-input-search :placeholder="$ct('menuName','输入菜单名称')" style="width: 100%" @search="onSearchMenu"/>
      </div>
      <div class="body">
        <a-tree
            :tree-data="searchTree"
            :replaceFields="{children:'children', title:'menuName', key:'id' }"
            :defaultExpandAll="true"
            v-if="showMenu"
            @select="selectTree"
        />
      </div>
    </div>
    <div class="page-common-content">
      <tool-bar
          @search="refreshTable()"
          @reset="resetTable()"
      >
        <template slot="toolBtn" slot-scope="scope">
          <a-button class="cu-btn-primary" icon="plus" @click="handleAdd()">{{$ct("add","新增")}}</a-button>
        </template>
        <template slot="toolForm">
          <a-form-item :label="$ct('keyword','关键字')">
            <a-input v-model="queryParam.keyword" :placeholder="$ct('keyword','关键字')"/>
          </a-form-item>
        </template>
      </tool-bar>
      <div style="height: calc(100% - 150px);">
        <a-spin :spinning="subTableLoading">
          <a-table
              ref="table"
              :columns="$toI18nFormat(subColumns)"
              :data-source="dataSource"
              size="small"
              :rowClassName="rowClassName"
              :customRow="rowClick"
              rowKey="uuid"
              showPagination="auto"
              :pagination="pagination"
              @change="handleTableChange"
              :key="subListKey"
              :scroll="scrollXY"
          >
						<template v-for="(item,index) in $toI18nFormat(subColumns)" :slot="item.slotName">
							<span>{{$ct(item.slotName,item.defaultTitle)}}</span>
						</template>
            <template slot="index" slot-scope="text,record,index">
              <span>{{index+1}}</span>
            </template>
            <span slot="renderAction" slot-scope="text,record">
							<template>
								<a @click="handleEdit(record)">{{$ct("edit","编辑")}}</a>
									<span class="action-margin"></span>
										<a @click="handleSub(record)" class="action-delete">{{$ct("delete","删除")}}</a>
									<span>
								</span>
							</template>
						</span>
          </a-table>
        </a-spin>
      </div>
      <sub-form ref="subModal"
				:visible="subVisible"
				:loading="subConfirmLoading"
				:model="subMdl"
				@cancel="handleCancel"
				@ok="handleOk"
				:groupData="groupData"
				:langData="langData"
      />

    </div>
  </div>
</template>

<script>
  import subForm from "./subEdit.vue";
  import {mapState} from "vuex";

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
    },
    onSelect: (record, selected, selectedRows) => {
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
    },
  };

  export default {
    name: "TableList",
    components: {
      subForm
    },
    computed: {
      ...mapState("setting", ["rowSelectColor"]),
      scrollXY() {
        let height = "";
        height = this.pageClientHeight - 40 - 40 - 22 - 105;
        const tdHeight = this.dataSource?.length * 40 ?? 0;
        return this.dataSource?.length >= 20 || height < tdHeight
          ? {y: height}
          : {};
      }
    },
    data() {
      return {
        rowKeys: "",
        subColumns: [
          {
            title: '序号',
            dataIndex: 'index',
						langCode: "serial",
            width: 50,
            scopedSlots: {
              customRender: "index"
            }
          },
          {
            title: '标识',
            dataIndex: 'langCode',
						langCode: "identification"
          },
          {
            title: '菜单名称',
            dataIndex: 'menuName'
          },
          {
            title: "操作",
            dataIndex: "action",
            width: 100,
            scopedSlots: {
              customRender: "renderAction"
            }
          },
        ],
        pageClientHeight: 0,
        subVisible: false,
        masterConfirmLoading: false,
        subConfirmLoading: false,
        subMdl: null,
        // 查询参数
        queryParam: {},
        masterUrl: {
          getMenu: '/system/menu/getTreeSysMenuData' //获取菜单数据
        },
        subUrl: {
          getGroup: '/system/sysLanguageConfig/selectByConfigType',
          getLang: '/system/sysLanguageConfig/selectByConfigType',
          saveGroup: '/system/sysLanguageConfig/save',
          saveLang: '/system/sysLanguageConfig/save',
          addData: '/system/sysLanguage/save',
          updateData: '/system/sysLanguage/update',
          deleteBatch: "/system/sysLanguage/deleteBatch",
        },
        innerUrl: '/system/sysDatabaseConnection/getColumn', //获取表字段数据地址
        dataSource: [],
        subTableLoading: false,
        langVisible: false,
        langConfirmLoading: false,
        treeData: [],
        searchTree: [],
        showMenu: false,
        langData: [], //语种数据
        groupVisible: false,
        groupConfirmLoading: false,
        groupData: [],
        subListKey: '',
        //菜单翻译
        visible: false,
        confirmLoading: false,
        mdl: null,
        pagination: {
          total: 0,
          current: 1,
          showTotal: (total, range) => {
            return this.$ct("tablePagingTotal","共 "+total+" 条",{total:total});
          },
          pageSize: 50,
          pageSizeOptions: ["50", "100", "150", "200"],
          showSizeChanger: true,
          showQuickJumper: true,
          onShowSizeChange: (current, pageSize) =>
            this.onShowSizeChange(current, pageSize),
        },
        rowSelection,
      };
    },
    mounted() {
      //获取菜单
      this.getMenu();
      //获取语言种类
      this.getLangType();
      this.refreshTable();
      this.resizeHandler();
    },
    methods: {
      // 重新调整表格高度
      resizeHandler() {
        // 获取页面内容的高度
        this.pageClientHeight = document.getElementsByClassName(
          "page-common-content"
        )[0]?.clientHeight;
      },
      //获取菜单数据
      getMenu() {
        this.$post(this.masterUrl.getMenu).then(res => {
          if (res.statusCode == 200) {
            this.treeData = JSON.parse(JSON.stringify(res.data))
            this.searchTree = JSON.parse(JSON.stringify(res.data))
            this.showMenu = true
          } else {
            this.$message.error(res.message, 1.5)
          }
        })
      },
      //获取多语言类型
      getLangType() {
        this.subTableLoading = true
        this.$post(this.subUrl.getLang, {}).then(res => {
          if (res.statusCode == 200) {
            this.langData = JSON.parse(JSON.stringify(res.data))
            //组装表头数据
            res.data.forEach((item, index) => {
              let obj = {
                title: item.configKey,
                dataIndex: item.configValue,
              }
              this.subColumns.splice(index + 2, 0, obj)
            })
            this.subTableLoading = false
          } else {
            this.$message.error(res.message, 1.5)
          }
        })
      },

      // 行点击事件
      rowClick(record, index) {
        const that = this;
        return {
          on: {
            click: () => {
              that.rowKeys = record['uuid'];
              that.rows = record;
              that.$emit("rowClick", record, index, that.rowKeys);
            },
          },
        };
      },
      selectTree(value, node, extra) {
        this.subListKey = new Date().getTime()
        this.menuId = value[0]
        this.queryParam.menuId = this.menuId
        this.refreshTable()
      },
      resetTable() {
        this.queryParam = {
					menuId: this.menuId
				};
        this.refreshTable();
      },
      //获取table数据
      refreshTable() {
        const that = this;
        that.subTableLoading = true
        that.dataSource = [];
				const pagination = {
					pageSize: this.pagination.pageSize,
					pageNo: this.pagination.current
				}
        const requestParameters = Object.assign({}, pagination, this.queryParam);
        that.$post('/system/sysLanguage/getPageSet', requestParameters).then(res => {
          if (res.statusCode == 200) {
            let data = res.data.rows
            const pager = {
              ...this.pagination,
            };
            pager.total = res.data.totalCount;
            this.pagination = pager;
            for (let i = 0; i < data.length; i++) {
              let obj = {
                key: data[i].uuid,
                langCode: data[i].langCode,
                ...JSON.parse(data[i].langJson),
                type: 'data',
                langClass: data[i].langClass,
                menuName: data[i].menuName,
                uuid: data[i].uuid,
              }
              that.dataSource.push(obj)
            }
            that.subTableLoading = false
          }
        })

      },
      // 表格行悬浮事件
      rowClassName(row) {
        if (this.rowSelectColor) {
          return row['uuid'] === this.rowKeys ? "row-select-color" : ""; // 每条数据的唯一识别值
        } else {
          return row['uuid'] === this.rowKeys ? "bg-bray" : ""; // 每条数据的唯一识别值
        }
      },
      handleAdd() {
        this.subMdl = {}
        this.$refs.subModal.title = this.$ct("add","新增")
        this.$refs.subModal.add();
        this.subVisible = true
        this.$refs.subModal.form.resetFields()
      },
      //编辑
      handleEdit(record) {
        this.$refs.subModal.title = this.$ct("edit","编辑")
        this.subMdl = {...record}
        this.$refs.subModal.edit(this.subMdl);
        //显示弹窗
        this.subVisible = true
      },
      handleOk() {
        this.subMdl = {}
        this.$refs.subModal.form.validateFields((errors, values) => {
          if (!errors) {
            if (!values.uuid) {
              //新增
              if (!this.menuId) {
                this.$message.warning('请先选择菜单！')
                return
              }
              let data = {
                menuId: this.menuId,
                langCode: values.langCode,
                langClass: values.langClass
              }
              let langObj = {}
              this.langData.forEach(item => {
                  langObj[item.configValue] = values[item.configValue]
                }
              )
              let allData = {...data, langJson: JSON.stringify(langObj)}
              this.$post(this.subUrl.addData, allData).then(res => {
                if (res.statusCode == 200) {
                  this.subVisible = false
                  //  重新获取table数据
                  this.refreshTable()
                } else {
                  this.$message.error(res.message, 1.5)
                }
              })
            } else {
              let data = {
                menuId: this.menuId,
                langCode: values.langCode,
                langClass: values.langClass,
                uuid: values.uuid
              }
              let langObj = {}
              this.langData.forEach(item => {
                  langObj[item.configValue] = values[item.configValue]
                }
              )
              let allData = {...data, langJson: JSON.stringify(langObj)}
              this.$post(this.subUrl.updateData, allData).then(res => {
                if (res.statusCode == 200) {
                  this.subVisible = false
                  //  重新获取table数据
                  this.refreshTable()
                } else {
                  this.$message.error(res.message, 1.5)
                }
              })
            }
          } else {
          }
        })
      },
      handleCancel() {
        this.subVisible = false
        this.subMdl = null
      },
      //删除数据
      handleSub(record) {
        let that = this
        this.$confirm({
          title: '提示',
          content: '确定删除该数据吗？删除之后不可恢复！',
          okText: '确定',
          cancelText: '取消',
          closable: true,
          icon: () => that.$createElement('a-icon', {
            props: {
              key: 'warning',
              type: 'exclamation-circle',
              twoToneColor: '#faad14'
            }
          }),
          onOk() {
            // 在这里调用删除接口
            that.$post(that.subUrl.deleteBatch, {uuid: record.uuid}).then(res => {
              if (res.statusCode == 200) {
                that.$message.success(res.message, 1.5)
                //  重新获取语言种类
                that.refreshTable()
              } else {
                that.$message.error(res.message, 1.5)
              }
            })
          },
          onCancel() {}
        })
      },
      //菜单搜索
      onSearchMenu(value) {
        this.searchTree = this.treeFilter(value, JSON.parse(JSON.stringify(this.treeData)))
      },
      //树形数据过滤
      treeFilter(value, arr) {
        if (!arr) {
          return []
        }
        let newarr = [];
        arr.forEach(item => {
          if (item.menuName) {
            if (item.menuName.indexOf(value) > -1) {
              let redata = this.treeFilter(value, item.children);
              let obj = {
                ...item,
                children: redata
              }
              newarr.push(obj);
            } else {
              if (item.children && item.children.length > 0) {
                let redata = this.treeFilter(value, item.children);
                let obj = {
                  ...item,
                  children: redata
                };
                if (redata && redata.length > 0) {
                  newarr.push(obj);
                }
              }
            }
          }
        });
        return newarr;
      },
      handleTableChange(pagination, filters, sorter) {
        const pager = {...this.pagination}
        pager.current = pagination.current
        this.pagination = pager
        this.refreshTable()
      },
      // 分页
      onShowSizeChange(current, pageSize) {
        const pager = {...this.pagination}
        pager.pageSize = pageSize
        this.pagination = pager
      },
      //监听resize
      initResizeEvent() {
        window.addEventListener("resize", this.resizeHandler, false);
      },
      //移除resize
      destroyResizeEvent() {
        window.removeEventListener("resize", this.resizeHandler);
      }
    }
  }
  ;
</script>

<style lang="less" scoped>
  .ant-table-small tr.ant-table-expanded-row td > .ant-table-wrapper {
    margin: 0px -8px 0px !important;
  }
  /deep/ tr.ant-table-expanded-row {
    background: #ffffff !important;
  }
  .page-common-left {
    display: flex;
    flex-direction: column;
    .header {
      display: flex;
      width: 100%;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #ebeef5;
      color: #606266;
      padding: 10px;
      height: 50px;
      box-sizing: border-box;
      .title {
        font-size: 16px;
      }
    }
    .body {
      padding: 10px;
      overflow: auto;
      flex: 1;
    }
  }
</style>

